<?php

namespace user;


use Phalcon\Security;

/**
 * Class user
 */
class User extends \Phalcon\Di\Injectable
{

    public function login($username, $password)
    {
        $data = [
            'username' => $username,
            'password' => $password
        ];
        $validation = new validation\Login();
        //进行验证
        if (!$validation->validate($data)) {
            return $validation->getErrorMessages();
        }
        if (isset($data['user_id'])) {
            return $this->loginLater($data['user_id']);
        } else {
            $info = model\user::findFirstByUsername($data['username']);
            //登录验证通过
            return $this->loginLater($info->id);
        }
    }

    /**
     * 登陆之后的操作
     * @param $user_id
     */
    private function loginLater($user_id)
    {
        return (int)$user_id;

    }

    /**
     * 注册用户
     * @param $username
     * @param $password
     * @param $password2
     * @return bool
     */
    public function reg($username, $password, $password2)
    {
        $data = [
            'username' => $username,
            'password' => $password,
            'password2' => $password2
        ];
        # 过滤
        $ft = new filterTool\Reg();
        $ft->filter($data);
        # 验证
        $va = new validation\Reg();
        if (!$va->validate($data)) {
            return $va->getErrorMessages();
        }
        $security = new Security();
        $data['password'] = $security->hash($data['password']);
        $data['forbid'] = 0;
        # 执行
        $usermodel = new model\user();
        if (!$usermodel->save($data)) {
            return $usermodel->getMessages();
        }

        return (int)$usermodel->id;

    }

}